package com.android.fragmentdemo
import android.Manifest
import android.content.Intent
import android.content.pm.PackageManager
import android.graphics.BitmapFactory
import android.graphics.Typeface
import android.net.Uri
import android.os.Build
import android.os.Bundle
import android.os.Environment
import android.os.Handler
import android.os.Looper
import android.provider.Settings
import android.text.Spannable
import android.text.SpannableString
import android.text.SpannableStringBuilder
import android.text.Spanned
import android.text.style.AbsoluteSizeSpan
import android.text.style.BackgroundColorSpan
import android.text.style.ForegroundColorSpan
import android.text.style.ImageSpan
import android.text.style.StrikethroughSpan
import android.text.style.StyleSpan
import android.text.style.UnderlineSpan
import androidx.core.app.ActivityCompat
import androidx.core.content.ContextCompat
import androidx.core.content.FileProvider
import com.hengfoxwolf.commonbase.base.BaseActivity2
import com.android.fragmentdemo.databinding.ActivityApkInstallBinding
import com.android.fragmentdemo.defineviews.CenterImageSpan
import com.android.fragmentdemo.defineviews.VerticalAlignTextSpan
import com.android.fragmentdemo.util.StringUtil
import java.io.File
import java.io.IOException

class ApkInstallActivity :
    BaseActivity2<ActivityApkInstallBinding>(ActivityApkInstallBinding::inflate) {

        private val INSTALL_PACKAGES_REQUESTCODE = 10011
        private val GET_UNKNOWN_APP_SOURCES = 10012

    override fun init(savedInstanceState: Bundle?) {

        //val pngPath = Environment.getExternalStorageDirectory().absolutePath + File.separator + "p01.jpg"
        //val bmp = BitmapFactory.decodeFile(pngPath)
        //mBinding.ivBmp.setImageBitmap(bmp)

        val bmpFile = File(Environment.getExternalStorageDirectory(),"data01.webp")
        val bmpUri = FileProvider.getUriForFile(
            this@ApkInstallActivity,
            "com.android.fragmentdemo.fileprovider",
            bmpFile
        )
        mBinding.ivBmp.setImageURI(bmpUri)


        // /storage/emulated/0
        mBinding.btnInstallApk.setOnClickListener {
            checkAndroidO()
        }


        val dataStr01 = resources.getString(R.string.title_activity_scrolling)
        val spannable01 = SpannableString(dataStr01)
        spannable01.setSpan(
            ForegroundColorSpan(resources.getColor(R.color.color_D8E65D8D)),
            0,
            3,
            SpannableString.SPAN_EXCLUSIVE_EXCLUSIVE
        )
        mBinding.textView01.text = spannable01

        val dataStr02 = resources.getString(R.string.txt_release_load_more)
        val spannable02 = SpannableString(dataStr02)
        spannable02.setSpan(
            BackgroundColorSpan(resources.getColor(R.color.color_AACF24)),
            3,
            5,
            SpannableString.SPAN_EXCLUSIVE_EXCLUSIVE
        )
        mBinding.textView02.text = spannable02


        val dataStr03 = resources.getString(R.string.txt_number_content_square)
        val spannable03 = SpannableString(dataStr03)
        spannable03.setSpan(
            AbsoluteSizeSpan(20),
            3,
            5,
            SpannableString.SPAN_EXCLUSIVE_EXCLUSIVE
        )
        mBinding.textView03.text = spannable03

        val dataStr04 = resources.getString(R.string.txt_color_square)
        val spannable04 = SpannableString(dataStr04)
        spannable04.setSpan(
            StyleSpan(Typeface.BOLD_ITALIC),
            2,
            5,
            SpannableString.SPAN_EXCLUSIVE_EXCLUSIVE
        )
        mBinding.textView04.text = spannable04

        val dataStr05 = resources.getString(R.string.txt_title_view)
        val spannable05 = SpannableString(dataStr05)
        spannable05.setSpan(
            StrikethroughSpan(),
            2,
            4,
            SpannableString.SPAN_EXCLUSIVE_EXCLUSIVE
        )
        mBinding.textView05.text = spannable05

        val dataStr06 = resources.getString(R.string.txt_ending_view)
        val spannable06 = SpannableString(dataStr06)
        spannable06.setSpan(
            UnderlineSpan(),
            2,
            4,
            SpannableString.SPAN_EXCLUSIVE_EXCLUSIVE
        )
        mBinding.textView06.text = spannable06


        val str0 = resources.getString(R.string.txt_detail)
        val str1 = resources.getString(R.string.txt_content_square)
        val spannableStringBuilder = SpannableStringBuilder()
        spannableStringBuilder.append(resources.getString(R.string.item_1))
        spannableStringBuilder.append(str0,ForegroundColorSpan(resources.getColor(R.color.color_D8E65D8D)),SpannableString.SPAN_EXCLUSIVE_EXCLUSIVE)
        spannableStringBuilder.append(resources.getString(R.string.item_2))
        spannableStringBuilder.append(str1,ForegroundColorSpan(resources.getColor(R.color.color_DC8717)),SpannableString.SPAN_EXCLUSIVE_EXCLUSIVE)
        mBinding.textView07.text = spannableStringBuilder

        val str3 = resources.getString(R.string.txt_title_view)
        val str4 = resources.getString(R.string.txt_family)
        val str5 = resources.getString(R.string.txt_start_animation)
        val spannableStringBuilder34 = SpannableStringBuilder()
        spannableStringBuilder34.append(str3)
        spannableStringBuilder34.append(str4,ForegroundColorSpan(resources.getColor(R.color.color_1D37CD)),SpannableString.SPAN_EXCLUSIVE_EXCLUSIVE)
        spannableStringBuilder34.append(
            str5,
            CenterImageSpan(resources.getDrawable(R.mipmap.ic_launcher), 10, 10),
            SpannableString.SPAN_EXCLUSIVE_EXCLUSIVE
        )
        spannableStringBuilder34.append(str5)

        /*val drawable = resources.getDrawable(R.mipmap.ic_launcher)
        drawable.setBounds(0, 0, drawable.intrinsicWidth, drawable.intrinsicHeight)
        val drawableSpanStr = SpannableString(str3)
        val imageSpan = ImageSpan(drawable, ImageSpan.ALIGN_CENTER)
        drawableSpanStr.setSpan(
            imageSpan,
            str3.length - 1,
            str3.length,
            Spannable.SPAN_INCLUSIVE_EXCLUSIVE
        )
        mBinding.textView08.text = drawableSpanStr*/


        //创建SpannableString对象
        val dataStr = "${str3}ABD"
        val sp = SpannableString(dataStr)
        //拿到所加图片的drawable对象
        val drawable = resources.getDrawable(R.mipmap.ic_launcher)
        drawable.setBounds(0, 0, drawable.intrinsicWidth, drawable.intrinsicHeight)
        //给SpannableString设置ImageSpan
        val imgSpace0 = resources.getDimension(R.dimen.dp_5).toInt()
        val imageSpan = CenterImageSpan(drawable,imgSpace0,imgSpace0)
        sp.setSpan(imageSpan, str3.length, dataStr.length, ImageSpan.ALIGN_BASELINE)
        //mBinding.textView08.text = sp

        val imgSpace1 = resources.getDimension(R.dimen.dp_5).toInt()
        val contentStr = resources.getString(R.string.txt_refresh_footer2)
        val targetPosition = 0.coerceAtLeast(20.coerceAtMost(contentStr.length)) //左小右大
        val spannableStringWithImg = SpannableString(StringUtil.getNewStrWithInsertPlaceHolder(contentStr, targetPosition))
        spannableStringWithImg.setSpan(
            CenterImageSpan(this@ApkInstallActivity, R.mipmap.ic_launcher, imgSpace1, imgSpace1),
            targetPosition,
            targetPosition + 1,
            Spanned.SPAN_EXCLUSIVE_EXCLUSIVE
        )
        spannableStringWithImg.setSpan(
            ForegroundColorSpan(resources.getColor(R.color.color_1D37CD)),
            6,
            10,
            SpannableString.SPAN_EXCLUSIVE_EXCLUSIVE
        )
        mBinding.textView08.text = spannableStringWithImg

        val centerStr = resources.getString(R.string.txt_content_desc)
        val centerSpannableStr = SpannableString(centerStr)
        centerSpannableStr.setSpan(
            AbsoluteSizeSpan(
                resources.getDimension(R.dimen.sp_22).toInt()
            ),
            2,
            3,
            Spannable.SPAN_INCLUSIVE_INCLUSIVE
        )
        centerSpannableStr.setSpan(
            VerticalAlignTextSpan(
                resources.getColor(R.color.color_E60C3F),
                resources.getDimension(R.dimen.dp_3),
                resources.getDimension(R.dimen.dp_3)
            ),
            2,
            3,
            Spannable.SPAN_INCLUSIVE_INCLUSIVE
        )
        mBinding.tvCenterVerticalContent.text = centerSpannableStr
    }

    private fun installApk() {
        //val file = File(Environment.getExternalStorageDirectory().absolutePath + File.separator + "Define.apk")
        val file0 = File(Environment.getExternalStorageDirectory(),"Define.apk")
        //如果没有设置 SDCard 写权限，或者没有 SDCard,apk 文件保存在内存中，需要授予权限才能安装
        try {
            val commandArr = listOf("chmod", "777", file0.toString())
            val processBuilder = ProcessBuilder(commandArr)
            processBuilder.start()
        } catch (ignored:IOException) {}
        val installIntent = Intent(Intent.ACTION_VIEW)
        installIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
        val apkUri : Uri
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            apkUri = FileProvider.getUriForFile(
                this@ApkInstallActivity,
                "com.android.fragmentdemo.fileprovider",
                file0
            )
            installIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION)
            installIntent.addCategory("android.intent.category.DEFAULT")
            installIntent.setDataAndType(apkUri, "application/vnd.android.package-archive")
        } else {
            apkUri = Uri.fromFile(file0)
            installIntent.setDataAndType(apkUri, "application/vnd.android.package-archive")
        }

        //查询所有符合intent跳转目标应用类型的应用，注意此方法必须放置在setDataAndType方法之后
        //val resolveLists = packageManager.queryIntentActivities(intent, PackageManager.MATCH_DEFAULT_ONLY)
        //然后全部授权
        //for (resolveInfo in resolveLists) {
        //    val packageName = resolveInfo.activityInfo.packageName
        //    grantUriPermission(packageName, apkUri, Intent.FLAG_GRANT_READ_URI_PERMISSION or Intent.FLAG_GRANT_WRITE_URI_PERMISSION)
        //}

        startActivity(installIntent)
    }

    private fun checkAndroidO() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            val canRequestPackageInstalls = packageManager.canRequestPackageInstalls()
            if (canRequestPackageInstalls) {
                installApk()
            } else {
                //请求安装未知应用来源的权限
                ActivityCompat.requestPermissions(this, arrayOf(Manifest.permission.REQUEST_INSTALL_PACKAGES), INSTALL_PACKAGES_REQUESTCODE)
            }
        } else {
            installApk()
        }
    }

    override fun onRequestPermissionsResult(
        requestCode: Int,
        permissions: Array<out String>,
        grantResults: IntArray
    ) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults)
        if (INSTALL_PACKAGES_REQUESTCODE == requestCode) {
            if (grantResults.isNotEmpty() && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                installApk()
            } else {
                val packageURI = Uri.parse("package:$packageName")
                val intent = Intent(Settings.ACTION_MANAGE_UNKNOWN_APP_SOURCES, packageURI)
                startActivityForResult(intent, GET_UNKNOWN_APP_SOURCES)
            }
        }
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (GET_UNKNOWN_APP_SOURCES == requestCode) {
            checkAndroidO()
        }
    }
}